package com.lmxdawn.api.admin.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lmxdawn.api.admin.annotation.AuthRuleAnnotation;
import com.lmxdawn.api.admin.entity.auth.AuthAdmin;
import com.lmxdawn.api.admin.req.OrderPageRequest;
import com.lmxdawn.api.admin.req.auth.AuthAdminQueryRequest;
import com.lmxdawn.api.admin.service.auth.AuthAdminService;
import com.lmxdawn.api.common.res.BaseResponse;
import com.lmxdawn.api.common.util.ResultVOUtils;
import com.lmxdawn.api.admin.entity.GoldCoin;
import com.lmxdawn.api.admin.service.IGoldCoinService;
import com.lmxdawn.api.dnf.dto.OrderTotalReq;
import com.lmxdawn.api.dnf.dto.OrderTotalVo;
import com.lmxdawn.api.dnf.service.impl.ExtraApplyServiceImpl;
import com.lmxdawn.api.dnf.util.GoldTypeEnum;
import com.lmxdawn.api.dnf.entity.Order;
import com.lmxdawn.api.dnf.entity.OrderItem;
import com.lmxdawn.api.dnf.service.OrderItemService;
import com.lmxdawn.api.dnf.service.OrderService;
import lombok.val;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * <p>
 * 代练服务 前端控制器
 * </p>
 *
 * @author huangyubin
 * @since 2024-07-05
 */
@RestController
@RequestMapping("/admin/dnf/order")
public class OrderManagerController {

    @Resource
    OrderService orderService;

    @Resource
    IGoldCoinService goldCoinService;

    @Resource
    OrderItemService orderItemService;

    @Resource
    AuthAdminService authAdminService;
    @Autowired
    private ExtraApplyServiceImpl extraApplyServiceImpl;

    @GetMapping("/{id}")
    public BaseResponse<Order> findById(@PathVariable String id) {
        Order order = orderService.findById(id);
        return ResultVOUtils.success(order);
    }


    @PostMapping("/total")
    public BaseResponse<OrderTotalVo> queryTotal(@RequestBody OrderTotalReq req) {
        OrderTotalVo orderTotalVo = orderService.queryTotal(req);
        return ResultVOUtils.success(orderTotalVo);
    }

    @PostMapping("/page")
    @AuthRuleAnnotation("admin/dnf/order/page")
    public BaseResponse page(@Valid @RequestBody OrderPageRequest pageRequest) {

        List<String> types = Arrays.asList(pageRequest.getType().split(","));
        String timeStart = CollUtil.isNotEmpty(pageRequest.getOrderTime()) ? pageRequest.getOrderTime().get(0) : "";
        String timeEnd = CollUtil.isNotEmpty(pageRequest.getOrderTime()) ? pageRequest.getOrderTime().get(1) : "";
        val page = orderService.page(Page.of(pageRequest.getPage(), pageRequest.getLimit()),
                Wrappers.<Order>lambdaQuery()
                        .likeRight(StrUtil.isNotBlank(pageRequest.getServer()), Order::getGameServer, pageRequest.getServer())
                        .between(CollUtil.isNotEmpty(pageRequest.getOrderTime()), Order::getCreateTime, timeStart, timeEnd )
                        .eq(StrUtil.isNotBlank(pageRequest.getPaymentStatus()), Order::getPaymentStatus, pageRequest.getPaymentStatus())
                        .eq(StrUtil.isNotBlank(pageRequest.getStatus()), Order::getStatus, pageRequest.getStatus())
                        .in(Order::getType, types)
                        .likeRight(Order::getId, StrUtil.equals(pageRequest.getTab(), "gold")
                                ? "A": StrUtil.equals(pageRequest.getTab(), "md") ? "M" :
                                StrUtil.equals(pageRequest.getTab(), "jade")? "B" : "D")
                        .orderByDesc(Order::getCreateTime)
        );
        List<Order> records = page.getRecords();
        if (CollUtil.isEmpty(records)){
            return ResultVOUtils.success(page);
        }
        List<AuthAdmin> authAdmins = authAdminService.listAll();
        val userMap = authAdmins.stream().collect(Collectors.toMap(AuthAdmin::getId, Function.identity()));
        Set<String> collect = records.stream().map(Order::getId).collect(Collectors.toSet());
//        Map<String, List<OrderItem>> listMap = orderItemService.lambdaQuery()
//                .in(OrderItem::getOrderId, collect).list().stream().collect(Collectors.groupingBy(OrderItem::getOrderId));
        List<GoldCoin> list = goldCoinService.list();
        Map<Long, GoldCoin> coinMap = list.stream().collect(Collectors.toMap(GoldCoin::getId, Function.identity()));
        records.forEach(r->{
            AuthAdmin authAdmin = new AuthAdmin();
            if (Arrays.asList(3,15).contains(r.getType())){
                authAdmin = userMap.get(r.getSaleId()) == null ?  new AuthAdmin(): userMap.get(r.getSaleId());
            }else{
                authAdmin = userMap.get(r.getUserId()) == null ?  new AuthAdmin(): userMap.get(r.getUserId());
            }
//            List<OrderItem> orderItems = listMap.get(r.getId());
//            StringBuilder sb = new StringBuilder();
//            if (CollUtil.isNotEmpty(orderItems)){
//                orderItems.forEach(item->{
//                    GoldCoin goldCoin = coinMap.get(item.getProductId());
//                    if (goldCoin == null){
//                        return;
//                    }
//                    GoldTypeEnum typeEnum = goldCoin.getType() == null ? null : GoldTypeEnum.match(goldCoin.getType());
//                    sb.append(typeEnum == null ? "" : typeEnum.getLabel() );
//                    sb.append(" : ");
//                    sb.append(item.getPrice());
//                    sb.append("(万金/元)");
//                    sb.append(" * ");
//                    sb.append(item.getQuantityOrder());
//                    sb.append(";");
//                });
//                r.setRate(orderItems.get(0).getPrice());
//            }

            val count = orderService.countMessage(r.getId(), "admin");
            r.setUnreadCount(count);
            r.setUserName(authAdmin.getUsername());
            r.setTel(authAdmin.getTel());
            r.setItemDesc(r.getRemark());
        });
        return ResultVOUtils.success(page);
    }

    @PostMapping("/save")
    @AuthRuleAnnotation("admin/dnf/order/save")
    public BaseResponse save(@Valid @RequestBody Order order) {
        return ResultVOUtils.success(orderService.save(order));
    }

    @PostMapping("/edit")
    @AuthRuleAnnotation("admin/dnf/order/edit")
    public BaseResponse edit(@Valid @RequestBody Order order) {
        return ResultVOUtils.success(orderService.updateById(order));
    }
    @PostMapping("/cancel")
    @AuthRuleAnnotation("admin/dnf/order/cancel")
    public BaseResponse cancel(@Valid @RequestBody Order order) {
        orderService.cancel(order);
        return ResultVOUtils.success();
    }

    @PostMapping("/take")
    @AuthRuleAnnotation("admin/dnf/order/take")
    public BaseResponse take(@Valid @RequestBody Order order) {
        orderService.takeOrder(order);
        return ResultVOUtils.success();
    }

    @PostMapping("/send")
    @AuthRuleAnnotation("admin/dnf/order/send")
    public BaseResponse send(@Valid @RequestBody Order order) {
        orderService.sendOrder(order);
        return ResultVOUtils.success();
    }


    @PostMapping("/confirmReceive")
    @AuthRuleAnnotation("admin/dnf/order/confirmReceive")
    public BaseResponse confirmReceive(@Valid @RequestBody Order order) throws InterruptedException {
        orderService.confirmReceive(order.getId().toString(), "admin", 1);
        return ResultVOUtils.success();
    }

    @PostMapping("/delete")
    @AuthRuleAnnotation("admin/dnf/order/delete")
    public BaseResponse delete(@Valid @RequestBody Order order) {
        return ResultVOUtils.success(orderService.removeById(order));
    }


    @PostMapping("/completed")
    @AuthRuleAnnotation("admin/dnf/order/take")
    public BaseResponse completed(@Valid @RequestBody Order order) {
        orderService.completed(order);
        return ResultVOUtils.success();
    }


    @PostMapping("/listOnlineUser")
    public BaseResponse listOnlineUser(AuthAdminQueryRequest request) {
        return ResultVOUtils.success(orderService.listOnlineUser(request));
    }
    @PostMapping("/fetchMessage")
    public BaseResponse fetchMessage(String roomId,String userId,Integer page) {
        return ResultVOUtils.success(orderService.fetchMessage(roomId, userId, page, null));
    }

    @PostMapping("/joinRoom")
    public BaseResponse joinRoom(String orderNo, HttpServletRequest request){
        // 获取房间信息
        return ResultVOUtils.success(orderService.joinRoom(orderNo, "web", null));
    }

}
